package com.skp.shaphan.actions;

import java.sql.Connection;
import java.sql.SQLException;

import oracle.jdbc.pool.OracleDataSource;

import com.skp.job.ProjectJobException;
import com.skp.shaphan.ShaphanApp;
import com.skp.shaphan.model.ConnectionDetails;
import com.skp.shaphan.ui.ConnectRunnable;
import com.skp.shaphan.ui.connectioncontrols.OracleConnectionOptions;

/**
 * Creates a connection to a database
 * @author Stephen Phillips
 *
 */
public class OracleConnectAction implements ConnectRunnable {
	private OracleConnectionOptions optionsGUI;
	private Connection connection;
	
	/**
	 * Creates the new action attached to a specific dialog
	 * @param serverConnectionOptions the dialog containing the connection information
	 */
	public OracleConnectAction(OracleConnectionOptions serverConnectionOptions) {
		this.optionsGUI = serverConnectionOptions;
	}
	
	/**
	 * Creates the connection and attaches it to the SQL Editor
	 */
	@Override
	public void run() {
		connect();
		if(connection != null) {
			ShaphanApp.getMainWindow().getSQLEditorsPane().setConnection(new ConnectionDetails(connection, ConnectionDetails.CONN_TYPE_ORACLE));
		}
	}

	@Override
	public Connection connect() {
		// http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#04_01
		// http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/111070_readme.html
		// http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_111060.html
		OracleDataSource ods;
		try {
			ods = new OracleDataSource();
		} catch (SQLException e) {
			(new ProjectJobException(e)).displayException();
			return null;
		}
		ods.setDriverType(optionsGUI.getConnectionType());
		ods.setUser(optionsGUI.getUser());
		ods.setPassword(optionsGUI.getPassword());
		if(optionsGUI.getDatabaseName().trim().length() > 0) {
			ods.setDatabaseName(optionsGUI.getDatabaseName());
		}
		ods.setNetworkProtocol("tcp");
		if(optionsGUI.getServerName().trim().length() > 0) {
			ods.setServerName(optionsGUI.getServerName());
		}
		if(optionsGUI.getServiceName().trim().length() > 0) {
			ods.setServiceName(optionsGUI.getServiceName());
		}
		if(optionsGUI.getPort().trim().length() > 0) {
			ods.setPortNumber(Integer.parseInt(optionsGUI.getPort()));
		}
		try {
			connection = ods.getConnection();
		} catch (SQLException e) {
			ProjectJobException.displayException(e);
		} catch (UnsatisfiedLinkError e) {
			(new ProjectJobException("Make sure the appropriate drivers are installed for Oracle.", e)).displayException();
		}
		return connection;
	}

}
